/**
 * zmn产品模块-产品列表
 * @author xujie
 * @since 2018/10/18
 */
layui.define(['index', 'form'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let layer = layui.layer;

    layui.use('laydate', function(){
        let laydate = layui.laydate;
        let _child = layui.$('.start-to-end-time');
        _child.each(function(index,item){
            //时间范围选择
            laydate.render({
                elem: item
                ,type: 'time'
                ,format: 'HH:mm'
                ,range: '~' //或 range: '~' 来自定义分割字符
                ,ready: formatMinutes
            });
        })
    });

    function formatMinutes() {
        layui.$(".laydate-time-list li ol").eq(2).parent("li").remove();
        layui.$(".laydate-time-list li ol").eq(4).parent("li").remove();
    }

    let plat = 10;

    zmnAppointmentSetting();

    function zmnAppointmentSetting (){

        $("#fcTime").hide();
        $("#entpTime").show();
        $("#spTime").hide();
        $("#userTime").show();

        $("#fcChangeTimeDiv").hide();
        $("#entpChangeTimeDiv").show();
        $("#spChangeTimeDiv").hide();
        $("#userChangeTimeDiv").show();

        $("#fcChangeNumberDiv").hide();
        $("#entpChangeNumberDiv").show();
        $("#spChangeNumberDiv").hide();
        $("#userChangeNumberDiv").show();
    }

    function yeyxAndYbwxAppointmentSetting (){

        $("#fcTime").show();
        $("#entpTime").hide();
        $("#spTime").show();
        $("#userTime").hide();

        $("#fcChangeTimeDiv").show();
        $("#entpChangeTimeDiv").hide();
        $("#spChangeTimeDiv").show();
        $("#userChangeTimeDiv").hide();

        $("#fcChangeNumberDiv").show();
        $("#entpChangeNumberDiv").hide();
        $("#spChangeNumberDiv").show();
        $("#userChangeNumberDiv").hide();
    }

    function cnhbAppointmentSetting (){

        $("#fcTime").hide();
        $("#entpTime").hide();
        $("#spTime").hide();
        $("#userTime").show();

        $("#fcChangeTimeDiv").hide();
        $("#entpChangeTimeDiv").hide();
        $("#spChangeTimeDiv").hide();
        $("#userChangeTimeDiv").show();

        $("#fcChangeNumberDiv").hide();
        $("#entpChangeNumberDiv").hide();
        $("#spChangeNumberDiv").hide();
        $("#userChangeNumberDiv").show();
    }

    layui.use('element', function(){
        let element = layui.element;
        //一些事件监听
        element.on('tab(demo)', function(data){
            plat = parseInt(data.elem.context.value);
            switch (plat) {
                case 10:
                    zmnAppointmentSetting();
                    break;
                case 20:
                    yeyxAndYbwxAppointmentSetting();
                    break;
                case 30:
                    yeyxAndYbwxAppointmentSetting();
                    break;
                case 40:
                    cnhbAppointmentSetting();
                    break;
            }
            fillData();
        });
    });

    fillData();

    function fillData(){
        let url = "/appointment/appointmentsetting/listQuery.action";
        let query = {
            plat: plat
        }
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(query),
            success:function(result) {
                if(result.status === 200) {
                    json.items = result.data;
                    assignment(result);
                }
            },
            error:function(XMLHttpRequest, textStatus, errorThrown){
            }
        })

    }

    function assignment(json){
        let fcAppointmentTime, entpAppointmentTime, opAppointmentTime, spAppointmentTime, engAppointmentTime, userAppointmentTime,
            fcChangeTime, entpChangeTime, opChangeTime, spChangeTime, engChangeTime, userChangeTime,
            fcChangeNumber, entpChangeNumber, opChangeNumber, spChangeNumber, engChangeNumber, userChangeNumber;
        let operationTime, operationContent = '', operator = '', html = '', maxNumber = 0;
        for (let i = 0, len = json.data.length; i < len; i++) {
            maxNumber++;
            let item = json.data[i];
            let time = item.startTime+' ~ '+item.endTime;
            let number = item.numberOfContractChanges;
            operationTime = dateFormat(new Date(item.updateTime), "yyyy-MM-dd hh:mm:ss");
            operationContent = '';
            if (item.updater == null) {
                operationContent += '新增';
                operator = item.creater;
            } else {
                operationContent += '修改';
                operator = item.updater;
            }
            if(item.appointmentOrChange === 1 && item.plat === plat){
                operationContent += '预约时间范围 -> ';
                switch (item.type) {
                    case 1:
                        fcAppointmentTime = time;
                        break;
                    case 2:
                        opAppointmentTime = time;
                        break;
                    case 3:
                        spAppointmentTime = time;
                        break;
                    case 4:
                        engAppointmentTime = time;
                        break;
                    case 5:
                        entpAppointmentTime = time;
                        break;
                    case 6:
                        userAppointmentTime = time;
                        break;
                }
            }

            if(item.appointmentOrChange === 2 && item.plat === plat){
                if (number != null) {
                    operationContent += '改约操作时间、改约次数 -> ';
                } else {
                    operationContent += '改约操作时间 -> ';
                }
                switch (item.type) {
                    case 1:
                        fcChangeTime = time;
                        fcChangeNumber = number;
                        break;
                    case 2:
                        opChangeTime = time;
                        opChangeNumber = number;
                        break;
                    case 3:
                        spChangeTime = time;
                        spChangeNumber = number;
                        break;
                    case 4:
                        engChangeTime = time;
                        engChangeNumber = number;
                        break;
                    case 5:
                        entpChangeTime = time;
                        entpChangeNumber = number;
                        break;
                    case 6:
                        userChangeTime = time;
                        userChangeNumber = number;
                        break;
                }
            }

            switch (item.type) {
                case 1:
                    operationContent += '厂商门户';
                    break;
                case 2:
                    operationContent += '运营平台';
                    break;
                case 3:
                    operationContent += '服务商门户';
                    break;
                case 4:
                    operationContent += '工程师app';
                    break;
                case 5:
                    operationContent += '政企门户';
                    break;
                case 6:
                    operationContent += '用户前端';
                    break;
            }
            if (maxNumber <= 8) {
                html += '<tr>' +
                    '        <td style="text-align: center;">' + operationTime +
                    '        <td style="text-align: center;">' + operationContent +
                    '        <td style="text-align: center;">' + operator +
                    '    </tr>';
            }
        }
        $('#operation').html(html);
        layui.use('form', function() {
            let form = layui.form;
            layui.$("#fcAppointmentTime").attr("value", fcAppointmentTime);
            form.val("zmn-form", {
                'fcAppointmentTime': fcAppointmentTime,
                'entpAppointmentTime': entpAppointmentTime,
                'opAppointmentTime': opAppointmentTime,
                'spAppointmentTime': spAppointmentTime,
                'engAppointmentTime': engAppointmentTime,
                'userAppointmentTime': userAppointmentTime,
                'fcChangeTime': fcChangeTime,
                'fcChangeNumber': fcChangeNumber,
                'opChangeTime': opChangeTime,
                'opChangeNumber': opChangeNumber,
                'spChangeTime': spChangeTime,
                'spChangeNumber': spChangeNumber,
                'engChangeTime': engChangeTime,
                'engChangeNumber': engChangeNumber,
                'entpChangeTime': entpChangeTime,
                'entpChangeNumber': entpChangeNumber,
                'userChangeTime': userChangeTime,
                'userChangeNumber': userChangeNumber
            });
            form.render(null, 'zmn-form');
        });
    }

    form.verify({
        number: function (value){
            if (value !== '') {
                let valueFlout = parseInt(value);
                if(valueFlout < 1){
                    return '改约次数不能小于1';
                }
            }
        }
    })

    form.on('submit(zmn-form-submit)', function(){

        let settings = [];
        let fcAppointmentTime = $("#fcAppointmentTime").val();
        if(!objectAssembly(settings, 1,1, fcAppointmentTime, null)){
            return false;
        }

        let opAppointmentTime = $("#opAppointmentTime").val();
        if(!objectAssembly(settings, 2,1,opAppointmentTime, null)){
            return false;
        }

        let spAppointmentTime = $("#spAppointmentTime").val();
        if(!objectAssembly(settings, 3,1,spAppointmentTime, null)){
            return false;
        }

        let engAppointmentTime = $("#engAppointmentTime").val();
        if(!objectAssembly(settings,4,1,engAppointmentTime, null)){
            return false;
        }

        let entpAppointmentTime = $("#entpAppointmentTime").val();
        if(!objectAssembly(settings,5,1, entpAppointmentTime,null)){
            return false;
        }

        let userAppointmentTime = $("#userAppointmentTime").val();
        if(!objectAssembly(settings,6,1, userAppointmentTime, null)){
            return false;
        }

        let fcChangeTime = $("#fcChangeTime").val();
        let fcChangeNumber = $("#fcChangeNumber").val();

        if(!objectAssembly(settings,1,2,fcChangeTime,fcChangeNumber)){
            return false;
        }

        let opChangeTime = $("#opChangeTime").val();
        let opChangeNumber = $("#opChangeNumber").val();
        if(!objectAssembly(settings,2,2,opChangeTime,opChangeNumber)){
            return false;
        }

        let spChangeTime = $("#spChangeTime").val();
        let spChangeNumber = $("#spChangeNumber").val();
        if(!objectAssembly(settings,3,2,spChangeTime,spChangeNumber)){
            return false;
        }

        let engChangeTime = $("#engChangeTime").val();
        let engChangeNumber = $("#engChangeNumber").val();
        if(!objectAssembly(settings,4,2,engChangeTime,engChangeNumber)){
            return false;
        }

        let entpChangeTime = $("#entpChangeTime").val();
        let entpChangeNumber = $("#entpChangeNumber").val();
        if(!objectAssembly(settings,5,2,entpChangeTime,entpChangeNumber)){
            return false;
        }

        let userChangeTime = $("#userChangeTime").val();
        let userChangeNumber = $("#userChangeNumber").val();
        if(!objectAssembly(settings,6,2,userChangeTime,userChangeNumber)){
            return false;
        }

        let url = "/appointment/appointmentsetting/addEditList.action";
        if(settings.length === 0){
            layer.msg("没有可修改内容");
            return false;
        }
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(settings),
            success:function(result) {
                if(result.status === 200) {
                    layer.msg(result.message);
                } else {
                    layer.msg(result.message, {"icon": 2});
                }
            },
            error:function(XMLHttpRequest, textStatus, errorThrown){
            }
        })
        return false;

    });

    //对象组装 type (1：厂商门户，2：运营平台，3：服务商门户，4：工程师app，5：政企门户，6：用户前端),
    // appointmentOrChange (1：预约，2：改约),time(时间),number(改约次数)
    function objectAssembly(settings,type,appointmentOrChange,time,number){

        if(time == null || time === '' ){
            if(number != null && number !== ''){
                layer.msg("改约次数没有对应的改约操作时间");
                return false;
            }
            return true;
        }
        let times = time.split('~');
        if (!checkStartEndTime(times[0], times[1])) {
            layer.msg("开始时间必须小于结束时间");
            return false;
        }
        let id = 0;
        for (let i = 0, len = json.items.length; i < len; i++){
            let item = json.items[i];
            if(item.type === type && item.appointmentOrChange === appointmentOrChange && item.plat === plat){
                if(time === item.startTime+' ~ '+item.endTime){
                    if(number != null && number !== ''){
                        number = parseInt(number);
                        if( item.numberOfContractChanges === number){
                            return true;
                        }
                    }else {
                        return true;
                    }
                }
                id = item.id;
                break;
            }
        }

        let setting = {
            id: id,
            plat: plat,
            type: type,
            appointmentOrChange: appointmentOrChange,
            startTime: times[0].trim(),
            endTime: times[1].trim(),
            numberOfContractChanges: number,
        };
        settings.push(setting);
        return true;
    }

    function checkStartEndTime(startTime, endTime) {

        startTime = parseInt(startTime.replace(':',''));
        endTime = parseInt(endTime.replace(':',''));
        return startTime < endTime;
    }

    function dateFormat(date, fmt) {

        let o = {
            "M+" : date.getMonth()+1,                 //月份
            "d+" : date.getDate(),                    //日
            "h+" : date.getHours(),                   //小时
            "m+" : date.getMinutes(),                 //分
            "s+" : date.getSeconds(),                 //秒
            "q+" : Math.floor((date.getMonth()+3)/3), //季度
            "S"  : date.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        for(let k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt;
    }

    //对外暴露的接口
    exports('plat_appointmentsetting_list', {});
});

